package com.example.mqtt.service;

import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class MqttProducerService {

    private final IMqttClient mqttClient;

    private final TaskService taskService;

    @Autowired
    public MqttProducerService(@Qualifier("mqttProducer") IMqttClient mqttClient, TaskService taskService) {
        this.mqttClient = mqttClient;
        this.taskService = taskService;
    }

//    @Scheduled(fixedRate = 60000) // 定时任务
    @Scheduled(fixedRate = 1000)
    public void produceData(){
        if (!taskService.isTaskEnabled()) {
            System.out.println("定时发送任务关闭中" + taskService.isTaskEnabled());
            return; // 如果任务被禁用，直接返回
        }
        try{
            System.out.println("启动定时发送任务...");
            // 检查连接状态
            if (!mqttClient.isConnected()) {
                System.out.println("MQTT连接断开，尝试重新连接...");
                mqttClient.reconnect();
            }
            double value = new Random().nextDouble();
            JSONObject data = new JSONObject().put("data", value);

            MqttMessage message = new MqttMessage(data.toString().getBytes());
            message.setQos(1);
            mqttClient.publish("sensor/topic", message); // 发布消息
        }catch (MqttException e) {
            System.out.println("MQTT操作失败");
            try {
                mqttClient.reconnect(); // 尝试重新连接
            } catch (MqttException ex) {
                System.out.println("MQTT重连失败");
            }
        } catch (Exception e) {
            System.out.println("发送消息异常");
        }

    }
}